package com.yueya.common.action;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Record;
import com.yueya.api.user.IUserService;
import com.yueya.common.constant.BaseConstant;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * ApiController
 */
@Before(ApiInterceptor.class)
public class ApiController extends Controller {

	public static Map<String, Object> jsonMap = new HashMap<String, Object>();

	public int getRows() {
		int rows = 20;
		if (getPara("rows") != null) {
			rows = getParaToInt("rows");
		}
		return rows;
	}

	public int getPage() {
		int page = 1;
		if (getPara("page") != null && getParaToInt("page") != 0) {
			page = getParaToInt("page");
		}

		return page;
	}

	public JSONObject getJson() {
		return JSONObject.fromObject(HttpKit.readData(getRequest()));
	}

	protected JSONArray getJsons() {
		return JSONArray.fromObject(HttpKit.readData(getRequest()));

	}

	/**
	 * 获取用户ID
	 * 
	 * @return
	 */
	protected String getUserId() {
		Record r = Duang.duang(IUserService.class).getUserByToken(getRequestToken());
		return r.getStr("user_id");
	}

	/**
	 * 获取用户对象
	 * 
	 * @return
	 */
	protected Record getUser() {
		return Duang.duang(IUserService.class).getUserByToken(getRequestToken());
	}

	private String getRequestToken() {
		return this.getRequest().getHeader(BaseConstant.TOKEN_KEY);
	}

}
